﻿using AutoMapper;
using B.S.XZYData.Api.Wrter.Application.Command.Account;
using B.S.XZYData.Domain.RBAC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System.Transactions;
using Yitter.IdGenerator;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Account
{
    public class UpdateAccountStateHandler : IRequestHandler<UpdateAccountStateCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<AccountModel> accountRepo;
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IBaseRepository<AccountRoleModel> accountroleRepo;
        private readonly IMapper mapper;
        private readonly ILogger<UpdateAccountStateHandler> logger;

        public UpdateAccountStateHandler(IBaseRepository<AccountModel> accountRepo,
            IBaseRepository<RoleModel> roleRepo,
            IBaseRepository<AccountRoleModel> accountroleRepo,
            IMapper mapper,
            ILogger<UpdateAccountStateHandler> logger)
        {
            this.accountRepo = accountRepo;
            this.roleRepo = roleRepo;
            this.accountroleRepo = accountroleRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 修改用户状态状态
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回统一包装类</returns>
        public async Task<ApiResult<int>> Handle(UpdateAccountStateCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();
            try
            {
                var acc = accountRepo.GetAll().Where(x => !x.IsDeleted && x.Id == request.AccountId).ToList().FirstOrDefault();
                if (acc == null)
                {
                    res.Msg = "该用户不存在";
                    res.Code = ApiEnum.Fail;
                    return await Task.FromResult(res);
                }
                acc.IsState = request.State;
                int r = await accountRepo.UpdateAsync(acc);
                
                if (r  > 0)
                {   
                    res.Data = r;
                    res.Msg = "修改用户状态状态成功";
                    res.Code = ApiEnum.Success;
                }
                else
                {
                    res.Data = r;
                    res.Msg = "修改用户状态状态失败";
                    res.Code = ApiEnum.Fail;
                }
                logger.LogInformation($"修改用户状态状态{acc.Name}成功");
                return await Task.FromResult(res);
            }
            catch (Exception ex)
            {
                logger.LogError("修改用户状态状态异常:" + ex.Message);
                res.Msg = "修改用户状态状态异常:" + ex.Message;
                res.Code = ApiEnum.Error;
                return await Task.FromResult(res);
            }
        }
    }
}
